<!-- 支付页面 -->
<template>
    <div class="box">
        <div>
            <h2>订单详情</h2>
        </div>
        <div v-for="item in order" v-if="state == 0">
            <div class="box2">
                <div class="top">
                    <div class="left">
                        <img :src="item.img" alt="">
                        <div style="width: 248px;text-align: left;">
                            <div
                                style="  overflow: hidden;white-space: nowrap; text-overflow: ellipsis; -o-text-overflow: ellipsis;">
                                {{ item.name }}
                                <div style=" margin-top: 16px;">
                                    <span
                                        style="display: inline-block;font-size: 12px;width: 126px;height: 18px;text-align: center; background-color: green;color: whitesmoke;">退货包运费险保障中></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="rigth">
                        <div style="font-size: 12px;margin-bottom: 10px;">￥<span style="font-size: 22px;color: red;">{{
                            item.price }}</span></div>

                        <div style="text-align: right;color: rgb(161, 161, 161);">x{{ item.num }}</div>
                        <div style="text-align: right;margin-top: 20px;">
                            <el-tag type="warning" v-if="goodsList.data.state == 0">待支付</el-tag>
                            <el-tag type="warning" v-if="goodsList.data.state == 1">待发货</el-tag>
                            <el-tag type="success" v-if="goodsList.data.state == 3">已发货</el-tag>
                        </div>

                    </div>
                </div>
                <div style="border-bottom: 1px solid rgb(185, 185, 185);"></div>
                <div style="text-align: left;margin-top: 10px;font-size: 14px;">
                    <span>该商品正在大促，直降 <span style="color: red;"> {{ pricereduction }}元</span></span>
                    <div class="ding" @click="toDetail">再次购买</div>
                </div>
                <div style="margin-top: 20px; text-align: right; font-size: 14px;">实付: <span
                        style="font-size: 16px;color: red;">￥{{ actualpayment }}</span> (免运费)</div>

            </div>
            <div class="bnt" v-for=" item in goodsList">
                <div style="margin-top: 10px;">订单编号：{{ item.uid }}</div>
                <div style="margin-top: 10px;">支付方式：微信</div>
                <div style="margin-top: 10px;">下单时间：{{ item.orderTime | str }}</div>
                <div style="margin-top: 10px;" v-if="goodsList.data.payTime != null">支付时间：{{ item.payTime }}</div>
            </div>
            <div class="zifu" v-if="isShow == true">
                <div style="margin-bottom: 10px;">
                    <div style="display: flex;justify-content: flex-end;">
                        订单待支付，请在<span style="color: red;"> <i class="el-icon-time"></i>{{ formattedTime }}</span> 内支付
                    </div>
                </div>
                <el-row>
                    <el-button type="warning" @click="postOrder">支付订单</el-button>
                    <el-button type="danger" @click="Delete">删除订单</el-button>
                </el-row>
            </div>
        </div>
        <div class="pay" v-if="state == 1">
            <img src="../assets/pay.png" alt="">
            <div style="margin-top: 20px;">跳转倒计时：{{ down }}</div>
            <div style="margin-top: 20px;">支付成功,即将返回订单页</div>
        </div>

        <div v-if="state == 2">
            <div>返回倒计时{{ down }}</div>
            <div>暂无订单数据，请前往下单</div>
        </div>
    </div>
</template>

<script>
import { update, deleteOrder } from '@/api/order'
export default ({
    data() {
        return {
            down: 3,
            goodsList: [],
            order: [],
            // 倒计时
            deadline3: Date.now() + 1000.5 * 60 * 30,
            stop: true,
            pricereduction: 0,//降价
            actualpayment: 0,//实付
            backendTime: null,    // 后端时间
            countdown: 0,         // 倒计时剩余时间
            formattedTime: '',
            isShow: true,
            Samplingtime: "",
            state: 0
        }
    },
    filters: {
        str: function (txt) {
            var dt = new Date(txt)
            var year = dt.getFullYear()
            var month = dt.getMonth() + 1
            var date = dt.getDate()
            var hours = dt.getHours()
            var minutes = dt.getMinutes()
            return `${year}-${month}-${date}:${hours}:${minutes}`
        }
    },

    created() {
        // this.timeFn()
        this.get()

    },

    computed: {

    },

    mounted() {
        this.backendTime = this.goodsList.data.orderTime
        console.log(this.backendTime)
        this.startCountdown();

        this.getCurrentTime();
        clearInterval(this.myTimeDisplay);
        this.myTimeDisplay = setInterval(() => {
            this.getCurrentTime(); //每秒更新一次时间
        }, 1000);

        this.toPer()
    },

    methods: {

        //下单完成跳转个人中心
        toPer() {
            if (this.state != 0) {
                setInterval(() => {
                    this.down--
                }, 1000)
                setTimeout(() => {
                    this.$router.push({
                        query: {
                            userId: this.goodsList.data.userId
                        },
                        path: "Personal"
                    })
                }, 3000)
            }
        },


        startCountdown() {
            if (this.goodsList.data.state == 0 || this.goodsList.data.state == null) {
                let currentTime = new Date();
                const endTime = new Date(this.backendTime).getTime() + 30 * 60 * 1000;  // 后端时间 + 30分钟的毫秒数
                const remainingTime = endTime - currentTime.getTime();
                this.countdown = Math.max(0, Math.floor(remainingTime / 1000));  // 将剩余时间转换为秒
                console.log(this.countdown)
                if (this.countdown > 0) {
                    setInterval(() => {
                        this.countdown--
                        this.formattedTime = this.formatTime(this.countdown)
                        // console.log(this.formattedTime)
                    }, 1000)
                } else {
                    var id = this.goodsList.data.id
                    deleteOrder(id).then(res => {
                        console.log(res)
                    })
                    this.$message.error("超时支付，请重新购买")
                }
            } else {
                this.isShow = false
                console.log("已经支付订单")
            }

        },

        getCurrentTime() {
            //获取当前时间并打印
            var _this = this;
            let yy = new Date().getFullYear();
            let mm = new Date().getMonth() + 1;
            let dd = new Date().getDate();
            let hh = new Date().getHours();
            let mf =
                new Date().getMinutes() < 10
                    ? "0" + new Date().getMinutes()
                    : new Date().getMinutes();
            let ss =
                new Date().getSeconds() < 10
                    ? "0" + new Date().getSeconds()
                    : new Date().getSeconds();
            _this.gettime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
            this.Samplingtime = _this.gettime;
        },

        // 倒计时
        hilarity() {
            this.$notify({
                message: "时间已到",
                duration: 0,
            });
        },

        // timeFn() {
        //     setInterval(() => {
        //         if (this.countdown > 0) {
        //             this.countdown--
        //         }
        //     }, 1000)
        // },

        get() {
            this.goodsList = {
                data: JSON.parse(this.$route.query.item)
            },
                this.order = this.goodsList.data.orderItem
            // console.log(this.goodsList)
            console.log(this.order)
            this.Pricereduction()
        },

        formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;

            const formattedMinutes = String(minutes).padStart(2, '0');
            const formattedSeconds = String(remainingSeconds).padStart(2, '0');

            return `${formattedMinutes}:${formattedSeconds}`;
        },

        //降价
        Pricereduction() {
            let red = Math.floor(((Math.random() * 89) + 11) / 10) / 10;
            let pricere = this.order[0].price * red

            //使用JavaScript的toFixed,可以把有很多小数点的值变成一位或两位小数点
            this.pricereduction = pricere.toFixed(1)
            let roundedValue = this.order[0].price - this.pricereduction
            this.actualpayment = roundedValue.toFixed(1)
        },

        //支付订单
        postOrder() {
            var arr = {
                id: this.goodsList.data.id,
                state: 1,
                payTime: this.Samplingtime
            }
            update(arr).then(res => {
                console.log(res)
                this.state = 1
                this.get()
                this.$message.success("支付成功")
                this.toPer()
            })
        },

        //删除订单
        Delete() {
            var id = this.goodsList.data.id
            this.$confirm("确定要删除此商品吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteOrder(id).then((res) => {
                        this.$message.success("删除成功")
                        this.state = 2
                        this.toPer()
                    })

                })
                .catch((e) => {
                    console.log(e);
                });
        },

        toDetail() {
            var data = this.order[0]
            var userId = this.goodsList.data.userId
            this.$router.push({
                query: {
                    id: data.commodityId,
                    img: data.img,
                    name: data.name,
                    price: data.price,
                    productDescription: data.productDescription,
                    userId: userId
                },
                path: 'detail'
            })
            console.log(data)
        }
    }
})
</script>

<style scoped>
.box {
    width: 800px;
    /* background-color: aqua; */
    margin: 0 auto;
    /* border: 1px black solid; */
}


.top {
    display: flex;

    /* background-color: #da7979; */
    /* width: 600px; */
    justify-content: space-between;
    margin-bottom: 22px;

}

.box2 {
    padding: 20px;
    box-shadow: 0px 2px 13px 5px #e6e6e6;
    margin: 0 auto;
}

.top .left {
    display: flex;
}

.top img {
    width: 130px;
    height: 130px;
    margin-right: 10px;
}

.top .rigth {
    left: 50px;
}



/* 再次购买按钮 */
.ding {
    display: inline;
    float: right;
    width: 72px;
    text-align: center;
    line-height: 24px;
    color: red;
    height: 24px;
    border-radius: 6px;
    border: 1px red solid;
}

.ding:hover{
    cursor: pointer;
}

.bnt {
    padding: 20px;
    box-shadow: 0px 2px 13px 5px #e6e6e6;
    margin: 20px auto;
    text-align: left;
    font-size: 14px;
    color: #777474;
}


.zifu {
    text-align: right;
    padding: 20px;
    box-shadow: 0px 2px 13px 5px #e6e6e6;
    margin: 0 auto;
}

/* 倒计时 */
.el-statistic {
    width: 142px;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    color: #000;
    font-variant: tabular-nums;
    list-style: none;
    font-feature-settings: "tnum";
    text-align: center;
}

.pay {}
</style>